package com.kingstar.ceres.config;

import com.kingstar.ceres.constants.CommonConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@Slf4j
@EnableAsync
public class CommonThreadPoolConfig {

    @Value("${com.kingstar.ceres.parse.corePoolSize}")
    private int corePoolSize = 10;

    @Value("${com.kingstar.ceres.parse.maxPoolSize}")
    private int maxPoolSize = 40;

    @Value("${com.kingstar.ceres.parse.queueSize}")
    private int queueSize = 50;

    private String prefix = "parse-thread-pool";

    @Value("${com.kingstar.ceres.save.corePoolSize}")
    private int saveCorePoolSize = 10;

    @Value("${com.kingstar.ceres.save.maxPoolSize}")
    private int saveMaxPoolSize = 40;

    @Value("${com.kingstar.ceres.save.queueSize}")
    private int saveQueueSize = 50;

    private String savePrefix = "save-thread-pool";

    @Bean("parseExecutor")
    public Executor parseExecutor() {

        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 配置核心线程数
        executor.setCorePoolSize(corePoolSize);
        // 配置最大线程数
        executor.setMaxPoolSize(maxPoolSize);
        // 配置队列大小
        executor.setQueueCapacity(queueSize);
        // 配置线程池中线程的名称前缀
        executor.setThreadNamePrefix(prefix);
        // 配置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        // 执行初始化
        executor.initialize();
        CommonConstants.THREAD_POOL_QUEUE=executor.getThreadPoolExecutor().getQueue();
        log.info("corePoolSize:{}; maxPoolSize:{}; queueCapacity:{}, threadNamePrefix:{}", corePoolSize, maxPoolSize, queueSize, prefix);
        return executor;
    }

//    @Bean("saveExecutor")
//    public Executor saveExecutor() {
//
//        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//        // 配置核心线程数
//        executor.setCorePoolSize(saveCorePoolSize);
//        // 配置最大线程数
//        executor.setMaxPoolSize(saveMaxPoolSize);
//        // 配置队列大小
//        executor.setQueueCapacity(saveQueueSize);
//        // 配置线程池中线程的名称前缀
//        executor.setThreadNamePrefix(savePrefix);
//        // 配置拒绝策略
//        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//        // 执行初始化
//        executor.initialize();
//        log.info("save corePoolSize:{}; maxPoolSize:{}; queueCapacity:{}, threadNamePrefix:{}", saveCorePoolSize, saveMaxPoolSize, saveQueueSize, saveCorePoolSize);
//        return executor;
//    }
}